package com.z.redis.command.impl.hash;

import com.z.redis.RedisCore;
import com.z.redis.command.CommandType;
import com.z.redis.command.WriteCommand;
import com.z.redis.datatype.BytesWrapper;
import com.z.redis.datatype.RedisData;
import com.z.redis.datatype.RedisHash;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import com.z.redis.resp.RespInt;
import io.netty.channel.ChannelHandlerContext;

public class Hset implements WriteCommand {
    private BytesWrapper key; // 哈希表的键
    private BytesWrapper field; // 字段
    private BytesWrapper value; // 值

    @Override
    public CommandType type(){
        return CommandType.hset;
    }

    @Override
    public void setContent(Resp[] array){
        key = ((BulkString) array[1]).getContent();
        field = ((BulkString) array[2]).getContent();
        value = ((BulkString) array[3]).getContent();
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        RedisData redisData = redisCore.get(key);
        if(redisData == null){ // 键不存在 创建哈希表
            RedisHash redisHash = new RedisHash();
            int put = redisHash.put(field, value); // 1 新增 0 更新
            redisCore.put(key, redisHash);
            ctx.writeAndFlush(new RespInt(put));
        }else if(redisData instanceof RedisHash) { // 键存在
            RedisHash redisHash = new RedisHash();
            int put = redisHash.put(field, value); // 1 新增 0 更新
            ctx.writeAndFlush(new RespInt(put));
        }else {
            throw new IllegalStateException("类型不匹配");
        }
    }

    @Override
    public void handle(RedisCore redisCore){
        RedisData redisData = redisCore.get(key);
        if(redisData == null){ // 键不存在 创建哈希表
            RedisHash redisHash = new RedisHash();
            int put = redisHash.put(field, value); // 1 新增 0 更新
            redisCore.put(key, redisHash);
        }else if(redisData instanceof RedisHash) { // 键存在
            RedisHash redisHash = new RedisHash();
            int put = redisHash.put(field, value); // 1 新增 0 更新
        }else {
            throw new IllegalStateException("类型不匹配");
        }
    }
}
